package pkg

import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v4/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/spf13/viper"
	"log"
)

func CreateClient() (_result *dysmsapi20170525.Client, err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(viper.GetString("sms.ak")),
		AccessKeySecret: tea.String(viper.GetString("sms.sk")),
	}

	config.Endpoint = tea.String(viper.GetString("sms.endpoint"))
	_result = &dysmsapi20170525.Client{}
	_result, err = dysmsapi20170525.NewClient(config)
	return _result, err
}

func SendSms(mobile, code string) (err error) {
	client, err := CreateClient()
	if err != nil {
		return err
	}
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		SignName:      tea.String(viper.GetString("sms.signName")),
		TemplateCode:  tea.String(viper.GetString("sms.templateCode")),
		PhoneNumbers:  tea.String(mobile),
		TemplateParam: tea.String("{\"code\":\"" + code + "\"}"),
	}
	runtime := &util.RuntimeOptions{}
	res, err := client.SendSmsWithOptions(sendSmsRequest, runtime)
	if err != nil {
		return err
	}
	if *res.Body.Code != "OK" {
		log.Println(res)
		return fmt.Errorf("短信验证码发送失败")
	}
	return
}
